package net.aiform.account.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import net.aiform.account.dao.PersonDao;
import net.aiform.account.model.Person;

@Transactional
public class PersonDaoJPA implements PersonDao {
	private EntityManager em;

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> findByCode(String code) {
		Query query = getEntityManager().createQuery("select p FROM Person p where expire is null and code = '" + code + "' ");
		return query.getResultList();
	}

	@Override
	public void save(Person person) {
		if (person.getId() == null) {
			em.persist(person);
		} else {
			em.merge(person);
		}
	}

	public EntityManager getEntityManager() {
		return em;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Override
	public void remove(String id) {
		Person person = find(id);
		if (person != null) {
			em.remove(person);
		}
	}

	@Override
	public Person find(String id) {
		return em.find(Person.class, id);
	}

}
